package com.example.suntest.service3;

import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.EnumMap;
import java.util.List;
import java.util.Map;

/**
 * @version 1.0
 * @Package: com.example.suntest.service3
 * @ClassName: ConverterHandler
 * @Author: sgq
 * @Date: 2024/7/11 9:29
 * @Description: 对象转换处理类：以此为入口进行对象转换方法调用
 */
@Service
public class ConverterHandler {

    @Resource
    private UserToUserDTOConverter userToUserDtoConverter;

    private Map<ConversionStrategy, Converter<?, ?>> converters = new EnumMap<>(ConversionStrategy.class);

    public ConverterHandler() {
        // 注册转换器
        converters.put(ConversionStrategy.USER_TO_USER_DTO, userToUserDtoConverter);
    }

    public <S, T> T convert(ConversionStrategy strategy, S source) {
        Converter<S, T> converter = getConverter(strategy);
        return converter.convert(source);
    }

    public <S, T> List<T> batchConvert(ConversionStrategy strategy, List<S> sources) {
        Converter<S, T> converter = getConverter(strategy);
        return converter.batchConvert(sources);
    }

    private <S, T> Converter<S, T> getConverter(ConversionStrategy strategy) {
        Converter<S, T> converter = (Converter<S, T>) converters.get(strategy);
        if (converter == null) {
            throw new IllegalArgumentException("根据策略未发现具体转换器类: " + strategy);
        }
        return converter;
    }
}
